package com.conversationboard.captcha;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.octo.captcha.service.CaptchaServiceException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * Servlet to generate a captcha image. Need to define a servlet mapping for
 * "captcha.jpg" and that will map to this servlet, which should make a response
 * as a JPG, as compared with all other servlets, which respond as though they
 * are HTML pages.
 * 
 * @author Keith Watson
 * 
 */

@WebServlet(name="CaptchaServlet", urlPatterns="/Pages/captcha.jpg")
public class CaptchaServlet extends HttpServlet {

    private static final long serialVersionUID = 8952562127306324743L;


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        byte[] captchaChallengeAsJpeg = null;

        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();

        try {

            String captchaId = request.getSession().getId();
            BufferedImage challenge = CaptchaService.getInstance().getImageChallengeForID(captchaId, request.getLocale());

            JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
            jpegEncoder.encode(challenge);

        } catch (IllegalArgumentException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        } catch (CaptchaServiceException e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

        /* Respond to the client page */

        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();

    }

}
